<template>
    <div class="users-manage">
      <div class="header">
        <div class="search">
          <el-input
            v-model="searchForm.email"
            placeholder="邮箱"
            clearable
          />
          <el-input
            v-model="searchForm.username"
            placeholder="用户名"
            clearable
          />
          <el-input
            v-model="searchForm.uid"
            placeholder="用户ID"
            clearable
          />
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="userList"
        border
        stripe
        class="user-table"
      >
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID" width="150" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="uid" label="uid" width="120" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'NORMAL' ? 'success' : 'danger'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              link
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
            <el-button 
              :type="row.status === 'NORMAL' ? 'warning' : 'success'" 
              link
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 'NORMAL' ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :pager-count="5"
          popper-class="custom-pagination"
        />
      </div>

      <el-dialog
        v-model="showEditDialog"
        title="编辑用户"
        width="500px"
      >
        <el-form :model="editForm" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="editForm.email" />
          </el-form-item>
          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="handleAvatarUpload"
            >
              <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar-preview">
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showEditDialog = false">取消</el-button>
            <el-button type="primary" @click="submitEdit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import { getUserList, deleteUser, search, start, updateUserInfo, uploadAvatar } from '@/api/admin'
  import { Plus } from '@element-plus/icons-vue'
  
  const loading = ref(false)
  const userList = ref([])
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  
  const searchForm = reactive({
    email: '',
    username: '',
    uid: ''
  })
  
  const loadUserList = async () => {
    try {
      loading.value = true
      const res = await getUserList(currentPage.value, pageSize.value)
      userList.value = res.data.list
      total.value = res.data.total
    } catch (error) {
      ElMessage.error('获取用户列表失败')
    } finally {
      loading.value = false
    }
  }
  
  const handleSearch = async () => {
    try {
      loading.value = true
      if (!searchForm.email && !searchForm.username && !searchForm.uid) {
        await loadUserList()
        return
      }
      
      const res = await search(
        searchForm.email || undefined,
        searchForm.username || undefined,
        searchForm.uid || undefined
      )
      
      if (res.data) {
        userList.value = Array.isArray(res.data) ? res.data : []
        total.value = userList.value.length
      } else {
        userList.value = []
        total.value = 0
      }
    } catch (error) {
      ElMessage.error('搜索失败：' + (error.message || '未知错误'))
    } finally {
      loading.value = false
    }
  }
  
  const handleSizeChange = (val) => {
    pageSize.value = val
    loadUserList()
  }
  
  const handleCurrentChange = (val) => {
    currentPage.value = val
    loadUserList()
  }
  
  const handleDelete = (row) => {
    ElMessageBox.confirm(
      '确认删除该用户？此操作不可恢复',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
      try {
        await deleteUser(row.id)
        ElMessage.success('删除成功')
        loadUserList()
      } catch (error) {
        ElMessage.error('删除失败')
      }
    })
  }
  
  const handleToggleStatus = async (row) => {
    try {
      await start(row.id)
      ElMessage.success('操作成功')
      loadUserList()
    } catch (error) {
      ElMessage.error('操作失败')
    }
  }
  
  const handleEdit = (row) => {
    editForm.id = row.id
    editForm.username = row.username
    editForm.email = row.email
    editForm.avatar = row.avatar
    showEditDialog.value = true
  }
  
  const submitEdit = async () => {
    try {
      await updateUserInfo(editForm)
      ElMessage.success('修改成功')
      showEditDialog.value = false
      loadUserList()
    } catch (error) {
      ElMessage.error('修改失败')
    }
  }
  
  const showEditDialog = ref(false)
  const editForm = reactive({
    id: '',
    username: '',
    email: '',
    avatar: ''
  })
  
  // 头像上传前的验证
  const beforeAvatarUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) {
      ElMessage.error('上传头像图片只能是图片格式!')
      return false
    }
    if (!isLt2M) {
      ElMessage.error('上传头像图片大小不能超过 2MB!')
      return false
    }
    return true
  }
  
  // 处理头像上传
  const handleAvatarUpload = async ({ file }) => {
    try {
      const res = await uploadAvatar(file)
      if (res.data?.url) {
        editForm.avatar = res.data.url
        ElMessage.success('上传成功')
      } else {
        ElMessage.error('上传失败')
      }
    } catch (error) {
      ElMessage.error('上传失败：' + (error.message || '未知错误'))
    }
  }
  
  onMounted(() => {
    loadUserList()
  })
  </script>
  
  <style scoped lang="scss">
  .users-manage {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    
    .header {
      margin-bottom: 20px;
      
      .search {
        display: flex;
        gap: 16px;
        
        .el-input {
          width: 200px;
        }
      }
    }
    
    .user-table {
      margin-bottom: 20px;
    }
    
    .pagination {
      display: flex;
      justify-content: flex-end;
    }

    :deep(.el-pagination) {
      .el-pagination__total {
        &::before {
          content: '总数量：';
        }
      }
      .el-pagination__jump {
        .el-pagination__goto {
          &::before {
            content: '去往';
          }
        }
      }
    }
  }

  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
  }

  .avatar-preview {
    width: 100px;
    height: 100px;
    display: block;
    object-fit: cover;
  }
  </style>